const app = getApp();
Page({

  /**
   * 页面的初始数据
   */
  data: {
    empty: false,
    show: false,
    cardList: [],
    list: [],
    rechargeMoney: 0,
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
    this.page = 1;
    this.getRecord();
    this.getCardList();
  },


  //获取水卡列表
  getCardList() {
    app.ajax({
      url: "User/WaterCard/waterCardList",
      data: {
        page: 1,
        row: 1000,
      },
      success: res => {
        if (res.data.code == 1000) {
          let cards = res.data.data;
          this.setData({
            cardList: cards
          })
        }
      }
    })
  },

  onShareAppMessage: function (res) {
    const {
      name,
      pic,
      id
    } = res.target.dataset;
    return {
      title: `你有一张${name}等待领取`,
      path: '/pages/sellCard/transfer/transfer?id=' + id,
      imageUrl: pic,
    }
  },





  //获取购买记录
  getRecord() {
    app.ajax({
      url: "User/Recharge/getMyCardList",
      data: {
        row: 15,
        page: this.page
      },
      success: res => {
        if (res.data.code == 1000) {
          const source = res.data.data;
          console.log('source.total_number', res.data.data, source.page.total_number)
          if (source.page.total_number == 0) {
            this.setData({
              empty: true
            })
          } else {
            let list;
            if (this.page == 1) { 
              list = source.data;
            } else {
              list = this.data.list.concat(source.data);
            }
            this.setData({
              list
            })
          }
        } else {
          app.showToast(res.data.message);
        }
      }
    })
  },

  //钩子函数  触底事件
  onReachBottom: function () {
    this.page++;
    this.getRecord();
  },

  radioChange(e) {
    this.card = e.detail.value;
  },

  confirm() {
    const card = this.card;
    if (!card) {
      app.showToast("选择充值水卡");
      return;
    }
    app.ajax({
      url: "User/Recharge/cardDeal",
      data: {
        card,
        id: this.id
      },
      success: res => {
        if (res.data.code == 1000) {
          app.showToast(res.data.message, "success");
          this.setData({
            show: false,
          })
          this.page = 1;
          this.getRecord();
        } else {
          app.showToast(res.data.message);
        }
      }
    })
  },

  //列表中的立即充值按钮
  recharge(e) {
    if (this.data.cardList.length == 0) {
      app.showToast("暂时还没有水卡可以选择");
      return;
    }
    const {
      id,
      free,
      money
    } = e.currentTarget.dataset;
    this.id = id;
    this.setData({
      show: true,
      rechargeMoney: (parseFloat(money) + parseFloat(free)).toFixed(2)
    })
  },


  navDetail(e) {
    const {
      id
    } = e.currentTarget.dataset;
    wx.navigateTo({
      url: '../buy-detail/buy-detail?id=' + id,
    })
    console.log(id);
  },

  //modal的取消按钮
  cancel() {
    this.setData({
      show: false
    })
  },
})